package com.fanrui.code.handle;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fanrui.code.chess.ChessGamerManager;
import com.fanrui.code.chess.ChessTableManager;
import com.fanrui.code.chess.IChessGamer;
import com.fanrui.code.chess.ITable;
import com.fanrui.code.chess.mahjong.AbstractMahjongTable;
import com.fanrui.code.chess.mahjong.MahjongGamer;
import com.fanrui.code.chess.mahjong.MatchMahjongTable;
import com.fanrui.code.chess.mahjong.PrivateMahjongTable;
import com.fanrui.code.chess.mahjong.round.MahjongOperationResponse;
import com.fanrui.code.common.annotation.Handle;
import com.fanrui.code.dao.EParameterType;
import com.fanrui.code.dao.ParameterConfigManager;
import com.fanrui.code.dao.TableLogDao;
import com.fanrui.code.entity.MahjongTableConfig;
import com.fanrui.code.entity.TableLog;
import com.fanrui.code.mahjong.util.MahjongCardUtil;
import com.fanrui.code.match.MatchManager;
import com.fanrui.code.match.TableConfig;
import com.fanrui.code.message.PlayerSession;
import com.fanrui.code.message.PlayerSessions;
import com.fanrui.code.message.RequestContext;
import com.fanrui.code.player.Player;
import com.fanrui.code.util.core.DateUtil;
import com.fanrui.proto.cmd.DetailedRecord;
import com.fanrui.proto.cmd.GamerIncome;
import com.fanrui.proto.cmd.GoldGameInfo;
import com.fanrui.proto.cmd.Mahjong;
import com.fanrui.proto.cmd.MahjongGameType;
import com.fanrui.proto.cmd.MahjongRoomInfo;
import com.fanrui.proto.cmd.MatchGameLevel;
import com.fanrui.proto.cmd.NotifyCanOperationCard;
import com.fanrui.proto.cmd.NotifyChat;
import com.fanrui.proto.cmd.NotifySomeoneIsAgreeDissolveMahjongRoom;
import com.fanrui.proto.cmd.NotifyZhuaMa;
import com.fanrui.proto.cmd.NotityPlayerLeaveMahjongDesk;
import com.fanrui.proto.cmd.Operation;
import com.fanrui.proto.cmd.Record;
import com.fanrui.proto.cmd.ReqCanOperation;
import com.fanrui.proto.cmd.ReqChangeGoldTable;
import com.fanrui.proto.cmd.ReqChat;
import com.fanrui.proto.cmd.ReqCreateMahjongRoom;
import com.fanrui.proto.cmd.ReqDissolveMahjongRoom;
import com.fanrui.proto.cmd.ReqEnterGodeGame;
import com.fanrui.proto.cmd.ReqGetClubRecordList;
import com.fanrui.proto.cmd.ReqGetGodeGameInfo;
import com.fanrui.proto.cmd.ReqGetMyDetailedRecordList;
import com.fanrui.proto.cmd.ReqGetMyRecordList;
import com.fanrui.proto.cmd.ReqJoinMahjongRoom;
import com.fanrui.proto.cmd.ReqObtainMahjongRoomInfo;
import com.fanrui.proto.cmd.ReqOperateDissolveMahjongRoom;
import com.fanrui.proto.cmd.ReqPlayerLeaveMahjongDesk;
import com.fanrui.proto.cmd.ReqPlayerOperation;
import com.fanrui.proto.cmd.ReqPrepare;
import com.fanrui.proto.cmd.ReqZhuaMa;
import com.fanrui.proto.cmd.ResChangeGoldTable;
import com.fanrui.proto.cmd.ResChat;
import com.fanrui.proto.cmd.ResCreateMahjongRoom;
import com.fanrui.proto.cmd.ResDissolveMahjongRoom;
import com.fanrui.proto.cmd.ResEnterGodeGame;
import com.fanrui.proto.cmd.ResGetClubRecordList;
import com.fanrui.proto.cmd.ResGetGodeGameInfo;
import com.fanrui.proto.cmd.ResGetMyDetailedRecordList;
import com.fanrui.proto.cmd.ResGetMyRecordList;
import com.fanrui.proto.cmd.ResJoinMahjongRoom;
import com.fanrui.proto.cmd.ResObtainMahjongRoomInfo;
import com.fanrui.proto.cmd.ResPlayerLeaveMahjongDesk;
import com.fanrui.proto.cmd.ResPlayerOperation;
import com.fanrui.proto.cmd.ResPrepare;

/**
 * 麻将请求处理类
 * @author Administrator
 *
 */
public class MahjongHandle {
	
	/**
	 * 获取匹配场房间
	 * 
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void getMatchRooms(Player player, RequestContext context, ReqGetGodeGameInfo req) {
		ResGetGodeGameInfo.Builder res = ResGetGodeGameInfo.newBuilder();
		res.addAllInfos(getMatchConfig());
		context.sendResponse(res.build());
	}
	
	
	private static List<GoldGameInfo> getMatchConfig() {
		Map<Integer, MahjongTableConfig> configs = TableConfig.getInstance().getAllMahjongConfigs();
		List<GoldGameInfo> result = new ArrayList<GoldGameInfo>();
		if (configs != null && !configs.isEmpty()) {
			for (MahjongTableConfig config : configs.values()) {
				result.add(configToCmd(config));
			}
		}
		return result;
	}
	
	public static GoldGameInfo configToCmd(MahjongTableConfig config) {
		GoldGameInfo.Builder builder = GoldGameInfo.newBuilder();
		builder.setName(config.getGameType() == 0 ? "赣州冲关" : "爆胡");
		builder.setMinGold(config.getEnterLimit());
		builder.setMaxGold(config.getLeaveLimit());
		builder.setLocalLimit(config.getLocalLimit());
		builder.setOnlineUsers(500);
		builder.setRoomType(MatchGameLevel.forNumber(config.getTableLevel()));
		builder.setType(MahjongGameType.forNumber(config.getGameType()));
		return builder.build();
	}
	
	
	/**
	 * 加入匹配场
	 * 
	 * @param player
	 * @param context
	 * @param req
	 *            void
	 */
	@Handle
	public void reqMatchMahjongGame(Player player, RequestContext context, ReqEnterGodeGame req) {
		ResEnterGodeGame.Builder res = ResEnterGodeGame.newBuilder();
		ResEnterGodeGame.Result result = MatchManager.getInstance().addMatchConditionCheck(player, req.getType(), req.getLevel());
		if(result == ResEnterGodeGame.Result.Success) {
			// 可以匹配，找到一个同等级的有空位置的房间
			res.setRoomID(MatchManager.getInstance().match(player, req.getType(), req.getLevel()));
		}
		res.setResult(result);
		context.sendResponse(res.build());
	}
	
	/**
	 * 匹配场换桌
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void reqMatchMahjongGame(Player player, RequestContext context, ResChangeGoldTable req) {
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		ReqChangeGoldTable.Builder res = ReqChangeGoldTable.newBuilder();
		MatchGameLevel level = null;
		MahjongGameType type = null;
		if (gamer != null) {// 先退出当前房间
			ITable table = gamer.getTable();
			if (table != null && table instanceof MatchMahjongTable) {
				MatchMahjongTable mtable = (MatchMahjongTable)table;
				level = mtable.getGameLevel();
				type = mtable.getGameType();
				ResPlayerLeaveMahjongDesk.Result result = table.exit(player.getId(), NotityPlayerLeaveMahjongDesk.Result.Unused);
				if(result != ResPlayerLeaveMahjongDesk.Result.Success) {
					res.setResult(ReqChangeGoldTable.Result.Failed);
					context.sendResponse(res.build());
					return;
				}
			}
		}
		ResEnterGodeGame.Result result = MatchManager.getInstance().addMatchConditionCheck(player, type, level);
		if(result == ResEnterGodeGame.Result.Success) {
			// 可以匹配，找到一个同等级的有空位置的房间
			res.setRoomID(MatchManager.getInstance().match(player, type, level));
		}
		res.setResult(ReqChangeGoldTable.Result.forNumber(result.getNumber()));
		context.sendResponse(res.build());
	}

	/**
	 * 创建麻将房间
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void createMahjongTable(Player player, RequestContext context, ReqCreateMahjongRoom req) {
		synchronized (player) {
			ResCreateMahjongRoom.Builder res = ResCreateMahjongRoom.newBuilder();
			// 在游戏中
			IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
			if (gamer != null) {
				res.setResult(ResCreateMahjongRoom.Result.StateError);
				context.sendResponse(res.build());
				return;
			}
			//是否有足够金币创建房间
			int cost = ParameterConfigManager.getInstance().getIntParameter(EParameterType.CreateTableConsumption);
			System.out.println(cost);
			
			// 创建房间
			ITable table;
			if(req.getClubId() != 0) {
				table = ChessTableManager.getInstance().create(req.getConfig(), req.getRoomer(), req.getClubId());
			}else {
				table = ChessTableManager.getInstance().create(req.getConfig(), req.getRoomer());
			}
			
			if (table == null) {
				res.setResult(ResCreateMahjongRoom.Result.Failed);
				context.sendResponse(res.build());
				return;
			}
			res.setRoomID(table.getID());
			res.setClubId((int)req.getClubId());
			res.setResult(ResCreateMahjongRoom.Result.Success);
			context.sendResponse(res.build());
		}
	}
	
	/**
	 * 加入房间
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void joinMahjongTable(Player player, RequestContext context, ReqJoinMahjongRoom req) {
		ITable table = ChessTableManager.getInstance().findByID(req.getRoomNum());
		ResJoinMahjongRoom.Builder builder = ResJoinMahjongRoom.newBuilder();
		ResJoinMahjongRoom.Result result = ResJoinMahjongRoom.Result.Failed;
		if (table != null) {
			// IP,安全距离
			PlayerSession session = PlayerSessions.getPlayerSession(context.getPlayerId());
			String ip = ((InetSocketAddress) session.getChannel().remoteAddress()).getAddress()
					.getHostAddress();
			player.setIp(ip);
			player.setX(req.getX());
			player.setY(req.getY());
			
			result = table.enter(player);
			builder.setRoomID(table.getID());
		}
		builder.setResult(result);
		context.sendResponse(builder.build());
	}

	/**
	 * 房间信息
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void checkRoomInfo(Player player, RequestContext context, ReqObtainMahjongRoomInfo req) {
		ITable table = ChessTableManager.getInstance().findByID(req.getRoomID());
		ResObtainMahjongRoomInfo.Builder builder = ResObtainMahjongRoomInfo.newBuilder();
		if(table != null) {
			builder.setRoomInfo((MahjongRoomInfo) table.toCmd());
			builder.setResult(ResObtainMahjongRoomInfo.Result.Success);
			if(table instanceof AbstractMahjongTable<?>) {
				AbstractMahjongTable<?> mahjongTable = (AbstractMahjongTable<?>) table;
				List<Mahjong> list = MahjongCardUtil.getInstance().toMahjongs(mahjongTable.getWannengMahjongs());
				builder.addAllMahjongs(list);
			}
		}else {
			builder.setErrorMsg("房间不存在");
			builder.setResult(ResObtainMahjongRoomInfo.Result.NotExist);
		}
		context.sendResponse(builder.build());
	}
	
	/**
	 * 玩家准备
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void ready(Player player, RequestContext context, ReqPrepare req) {
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		ResPrepare.Builder res = ResPrepare.newBuilder();
		if (gamer != null && gamer.getTable() != null) {
			gamer.getTable().playerReady(gamer);
			res.setResult(ResPrepare.Result.Success);
		}else {
			res.setResult(ResPrepare.Result.Failed);
		}
		context.sendResponse(res.build());
	}
	
	/**
	 * 玩家进行操作
	 * 
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void playerOperation(Player player, RequestContext context, ReqPlayerOperation req) {
		MahjongGamer gamer = ChessGamerManager.getInstance().findGamer(player.getId(), MahjongGamer.class);
		ResPlayerOperation.Builder res = ResPlayerOperation.newBuilder();
		if (gamer != null) {
			AbstractMahjongTable<?> table = gamer.getTable();
			if(table != null) {
				MahjongOperationResponse response = new MahjongOperationResponse();
				response.setCard(req.getMj());
				response.setCards(MahjongCardUtil.getInstance().toMahjongCard(req.getMjsList()));
				response.setOperationId(player.getId());
				response.setType(req.getType());
				response.setTable(table);
				ResPlayerOperation.Result result = table.addPlayerResponse(response);
				if (result == ResPlayerOperation.Result.Success) {
					gamer.clearWaitOperatoion();
					table.playerSuccessCallResponse();
				}
				res.setResult(result);
			}
		}
		context.sendResponse(res.build());
	}
	
	/**
	 * 玩家离开房间
	 * 
	 * @param player
	 * @param context
	 * @param req
	 *            void
	 */
	@Handle
	public void leavelMahjongDesk(Player player, RequestContext context, ReqPlayerLeaveMahjongDesk req) {
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		ResPlayerLeaveMahjongDesk.Builder res = ResPlayerLeaveMahjongDesk.newBuilder();
		if (gamer != null) {
			ITable table = gamer.getTable();
			if (table != null) {
				ResPlayerLeaveMahjongDesk.Result result = table.exit(player.getId(), NotityPlayerLeaveMahjongDesk.Result.Unused);
				res.setResult(result);
			} else {
				res.setResult(ResPlayerLeaveMahjongDesk.Result.NotInRoom);
			}
		} else {
			res.setResult(ResPlayerLeaveMahjongDesk.Result.NotInRoom);
		}
		context.sendResponse(res.build());
	}
	
	/**
	 * 请求解散房间
	 * 
	 * @param player
	 * @param context
	 * @param req
	 *            void
	 */
	@Handle
	public void dissolveMahjongRoom(Player player, RequestContext context, ReqDissolveMahjongRoom req) {
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		ResDissolveMahjongRoom.Builder res = ResDissolveMahjongRoom.newBuilder();
		if (gamer != null) {
			ITable table = gamer.getTable();
			if (table != null && table instanceof PrivateMahjongTable) {
				ResDissolveMahjongRoom.Result result = ((PrivateMahjongTable) table).playerReqDissolveTable(gamer, true);
				res.setResult(result);
				if (result == ResDissolveMahjongRoom.Result.Success) {
					NotifySomeoneIsAgreeDissolveMahjongRoom.Builder notify = NotifySomeoneIsAgreeDissolveMahjongRoom.newBuilder();
					notify.addAgreeList(player.getNickname());
					notify.addRefuseList("");
					notify.setApplicant(player.getNickname());
					table.broadcast(notify.build());
				}
			} else {
				res.setResult(ResDissolveMahjongRoom.Result.NotInRoom);
			}
		} else {
			res.setResult(ResDissolveMahjongRoom.Result.NotInRoom);
		}
		context.sendResponse(res.build());
	}

	/**
	 * 同意或拒绝解散房间
	 * 
	 * @param player
	 * @param context
	 * @param req
	 *            void
	 */
	@Handle
	public void reqOperateDissolveMahjongRoom(Player player, RequestContext context,
			ReqOperateDissolveMahjongRoom req) {
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		ResDissolveMahjongRoom.Builder res = ResDissolveMahjongRoom.newBuilder();
		if (gamer != null) {
			ITable table = gamer.getTable();
			if (table != null && table instanceof PrivateMahjongTable) {
				ResDissolveMahjongRoom.Result result = ((PrivateMahjongTable) table)
						.playerReqDissolveTable(gamer, req.getIsAgree());
				res.setResult(result);
				if (result == ResDissolveMahjongRoom.Result.Success) {
					NotifySomeoneIsAgreeDissolveMahjongRoom.Builder notify = NotifySomeoneIsAgreeDissolveMahjongRoom
							.newBuilder();
					if(req.getIsAgree()) {
						notify.addAgreeList(player.getNickname());
					}else {
						notify.addAgreeList(player.getNickname());
					}
					notify.setApplicant(req.getApplicant());
					notify.addAllAgreeList(req.getAgreeListList());
					notify.addAllRefuseList(req.getRefuseListList());
					table.broadcast(notify.build());
				}
			} else {
				res.setResult(ResDissolveMahjongRoom.Result.NotInRoom);
			}
		} else {
			res.setResult(ResDissolveMahjongRoom.Result.NotInRoom);
		}
		context.sendResponse(res.build());
	}
	
	/**
	 * 是否能够操作的通知
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void reqCanOperation(Player player, RequestContext context, ReqCanOperation req) {
		MahjongGamer gamer = (MahjongGamer) ChessGamerManager.getInstance().findGamer(player.getId());
		if (gamer != null) {
			List<Operation> list  = gamer.canOperationCardListMySelf(null);
			if(list != null && !list.isEmpty()) {
				NotifyCanOperationCard.Builder notify = NotifyCanOperationCard.newBuilder();
				for(Operation op : list) {
					notify.addOperation(op);
				}
				notify.setOperationMahjong(gamer.getCurrendResponse().getCard().toCardCmd());
				gamer.send(notify.build());
			}
		}
	}
	
	/**
	 * 游戏内聊天
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void chat(Player player, RequestContext context, ReqChat req) {
		ResChat.Builder res = ResChat.newBuilder();
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		ResChat.Result result = ResChat.Result.Failed;
		if (gamer != null) {
			ITable table = gamer.getTable();
			if(table != null) {
				NotifyChat.Builder notify = NotifyChat.newBuilder();
				notify.setChatMsg(req.getChatMsg());
				notify.setUserID(player.getId());
				table.broadcast(notify.build());
				result = ResChat.Result.Success;
			}
		}
		res.setResult(result);
		context.sendResponse(res.build());
	}
	
	/**
	 * 赢家抓马
	 * @param player
	 * @param context
	 * @param req
	 */
	@Handle
	public void zhuaMa(Player player, RequestContext context, ReqZhuaMa req) {
		IChessGamer<?> gamer = ChessGamerManager.getInstance().findGamer(player.getId());
		if (gamer != null) {
			ITable table = gamer.getTable();
			if(table != null) {
				NotifyZhuaMa.Builder notify = NotifyZhuaMa.newBuilder();
				notify.setMapai(req.getMapai());
				table.broadcast(notify.build());
			}
		}
	}
	
	/**
	 * 查询房间内的所有战绩
	 * @param gamer
	 * @param context
	 * @param req
	 */
	@Handle
	public void reqGetMyDetailedRecordList(Player gamer, RequestContext context, ReqGetMyDetailedRecordList req) {
		ResGetMyDetailedRecordList.Builder res = ResGetMyDetailedRecordList.newBuilder();
		//根据房间号查询房间内战绩
		List<Integer> tableIds = new ArrayList<>();
		tableIds.add(req.getRecordID());
		List<TableLog> allTableLogs =  TableLogDao.getInstance().selectTablLogs(tableIds);
		if(allTableLogs != null && !allTableLogs.isEmpty()) {
			// 将同一局的战绩放到同一个集合里面
			Map<Integer, List<TableLog>> sort = new HashMap<Integer, List<TableLog>>();
			for(TableLog tableLog : allTableLogs){
				List<TableLog> list = null;
				if(!sort.containsKey(tableLog.getInning())){
					list = new ArrayList<>();
					sort.put(tableLog.getInning(), list);
				}else{
					list = sort.get(tableLog.getInning());
				}
				list.add(tableLog);
			}
			// 生成命令
			for(int inning : sort.keySet()){
				List<TableLog> list = sort.get(inning);
				DetailedRecord.Builder detailedRecord = DetailedRecord.newBuilder();
				detailedRecord.setBoardNum(inning);
				if(list != null && !list.isEmpty()) {
					for (TableLog tableLog : list) {
						GamerIncome.Builder gamerIncome = GamerIncome.newBuilder();
						gamerIncome.setIncome(tableLog.getIncome());
						gamerIncome.setNickname(tableLog.getPlayerName());
						detailedRecord.addIncomeList(gamerIncome.build());
						detailedRecord.setTime(tableLog.getLogTime().getTime());
						detailedRecord.setToken(tableLog.getLogToken());
					}
				}
				res.addDetailedRecordList(detailedRecord.build());
			}
		}
		context.sendResponse(res.build());
	}
	
	/**
	 * 总战绩查询
	 * @param gamer
	 * @param context
	 * @param req
	 */
	@Handle
	public void reqGetMyRecordList(Player player, RequestContext context, ReqGetMyRecordList req) {
		ResGetMyRecordList.Builder res = ResGetMyRecordList.newBuilder();
		SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
		Date yesterday = DateUtil.getYesterday();
		// 前两天的时间
		Date beforeYesterday = DateUtil.getYesterday(yesterday);
//		String date2 = format.format(beforeYesterday);
		
		// 前三天的时间
		Date doubleBeforeYesterday = DateUtil.getYesterday(beforeYesterday);
		String date3 = format.format(doubleBeforeYesterday);
		List<Integer> tableLogs = TableLogDao.getInstance().getPlayerJoinTableIds(player.getId(), date3);
		List<Record> recordList = new ArrayList<Record>();
		if (tableLogs != null && !tableLogs.isEmpty()) {
			List<TableLog> allTableLogs =  TableLogDao.getInstance().selectTablLogs(tableLogs);
			if(allTableLogs != null && !allTableLogs.isEmpty()){
				// 将相同房间号的房间放到同一个集合里面
				Map<Integer, List<TableLog>> sort = new HashMap<Integer, List<TableLog>>();
				for(TableLog tableLog : allTableLogs){
					List<TableLog> list = null;
					if(!sort.containsKey(tableLog.getTableId())){
						list = new ArrayList<>();
						sort.put(tableLog.getTableId(), list);
					}else{
						list = sort.get(tableLog.getTableId());
					}
					list.add(tableLog);
				}
				
				// 生成命令
				for(int tableId : sort.keySet()){
					int income = 0;
					int boardNum = 0;
					Record.Builder record = Record.newBuilder();
					record.setRoomID(tableId);
					List<TableLog> roomTableLog = sort.get(tableId);
					if (roomTableLog != null && !roomTableLog.isEmpty()) {
						for (TableLog tableLog : roomTableLog) {
							if(tableLog.getPlayerId().equals(player.getId())) {
								income += tableLog.getIncome();
								if(tableLog.getInning() > boardNum) {
									boardNum = tableLog.getInning();
								}
								record.setTime(tableLog.getLogTime().getTime()+"");
							}
						}
					}
					record.setIncome(income);
					record.setBoardNum(boardNum);
					recordList.add(record.build());
				}
			}
		}
		res.addAllRecordList(recordList);
		context.sendResponse(res.build());
	}
	
	/**
	 * 俱乐部战绩查询
	 * @param gamer
	 * @param context
	 * @param req
	 */
	@Handle
	public void reqGetClubRecordList(Player player, RequestContext context, ReqGetClubRecordList req) {
		ResGetClubRecordList.Builder res = ResGetClubRecordList.newBuilder();
		SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
		Date yesterday = DateUtil.getYesterday();
		// 前两天的时间
		Date beforeYesterday = DateUtil.getYesterday(yesterday);
//		String date2 = format.format(beforeYesterday);
		
		// 前三天的时间
		Date doubleBeforeYesterday = DateUtil.getYesterday(beforeYesterday);
		String date3 = format.format(doubleBeforeYesterday);
		List<Integer> tableLogs = TableLogDao.getInstance().getClubTableIds(req.getClubid(), date3);
		List<Record> recordList = new ArrayList<Record>();
		if (tableLogs != null && !tableLogs.isEmpty()) {
			List<TableLog> allTableLogs =  TableLogDao.getInstance().selectTablLogs(tableLogs);
			if(allTableLogs != null && !allTableLogs.isEmpty()){
				// 将相同房间号的房间放到同一个集合里面
				Map<Integer, List<TableLog>> sort = new HashMap<Integer, List<TableLog>>();
				for(TableLog tableLog : allTableLogs){
					List<TableLog> list = null;
					if(!sort.containsKey(tableLog.getTableId())){
						list = new ArrayList<>();
						sort.put(tableLog.getTableId(), list);
					}else{
						list = sort.get(tableLog.getTableId());
					}
					list.add(tableLog);
				}
				
				// 生成命令
				for(int tableId : sort.keySet()){
					int income = 0;
					int boardNum = 0;
					Record.Builder record = Record.newBuilder();
					record.setRoomID(tableId);
					List<TableLog> roomTableLog = sort.get(tableId);
					if (roomTableLog != null && !roomTableLog.isEmpty()) {
						for (TableLog tableLog : roomTableLog) {
							if(tableLog.getPlayerId().equals(player.getId())) {
								income += tableLog.getIncome();
								if(tableLog.getInning() > boardNum) {
									boardNum = tableLog.getInning();
								}
								record.setTime(tableLog.getLogTime().getTime()+"");
							}
						}
					}
					record.setIncome(income);
					record.setBoardNum(boardNum);
					recordList.add(record.build());
				}
			}
		}
		res.addAllRecordList(recordList);
		context.sendResponse(res.build());
	}
}
